/**
 * 基于 angular 扩展的 ui 控件
 */
define(function (require, exports, module) {
    var $ = require("jquery");
    var angular = require("angular");
    var _ = require("underscore");
    var util = require("util");
    var ui = require("ui");
    require('jqtree');
    var projectSelector = angular.module('projectTreeSelector', []);

    // 项目树控件
    var projectDirective = function ($compile, $document, $parse) {
        return {
            restrict: 'EA',
            replace: true,
            transclude: true,
            require: '?ngModel',
            template: ['',
                '<span class="select-border js-select fl select" style="z-index:100;">',
                '<input id="projTreeInput" style="cursor:pointer" class="select-text" readonly type="text" ng-model="curProject_name" placeholder="">',
                '<span class="select-icon"><i class="select-icon-arrow"></i></span>',
                '<div style="display:none;background:#fff;" class="proj_tree_wrap mt30" id="projTreeContainer">',
                '<div class="search-box-border" style="margin:0"><input type="text" placeholder="请输入关键字" class="search-box"></div>',
                '<div id="proj_tree_table" class="" style="max-height:250px;overflow:auto;border-bottom:1px solid #d9d9d9;"></div>',
                '</div>',
                '</span>'].join(""),
            scope: {
                data: '=data'
            },
            link: function (scope, element, attrs, ngModel) {

                var projTreeInput = element.find('#projTreeInput');
                var projTreeContainer = element.find('#projTreeContainer');

                /**
                 * 生成jqtree可用的projdata
                 */
                var jqtree_i = 0
                function getProjTreeData (data) {
                    jqtree_i++;
                    angular.forEach(data, function (item) {
                        item.children = item.children || item.list;
                        item.name = item.name ? item.name : item.ProjName;
                        item.id = item.id ? item.id : item.p_projectId ;
                        item.level = jqtree_i;
                        getProjTreeData(item.children);
                    });
                    -- jqtree_i;
                    return data;
                }

                function findProject (projId,data) {
                    for (var i = 0; i < data.length; i++) {
                        var result;
                        var item = data[i];
                        if (item.id === projId) {
                            result = item;
                        } else {
                            result = findProject(projId,item.children || []);
                        }
                        if (result) {
                            return result;
                        }
                    }
                    return null;
                }
                /**
                 * 过滤树数据
                 * @returns {*}
                 */

                function getFilterTreeData(data,key,value){
                    if (!data || !key) return [];
                    var result = [];
                    value = value.toLowerCase();
                    for (var i = 0, l = data.length; i < l; i++) {
                        var inArray = false;
                        if (typeof data[i][key] == "string" && data[i][key].toLowerCase().indexOf(value)>-1) {
                            result.push(data[i]);
                            inArray = true;
                        }
                        if (inArray && data[i].children && data[i].children.length) {

                        } else {
                            result = result.concat(getFilterTreeData(data[i]['children'], key, value));
                        }
                    }
                    return result;
                }

                function toggleContainer () {

                    if (projTreeContainer.css('display') === 'none') {
                        open();
                    } else {
                        collapse();
                    }
                }

                projTreeInput.bind('click',function(){
                    toggleContainer();
                });

                scope.$watch('data',function(projectList){
                    if (projectList) {
                        var $tree = element.find('#proj_tree_table');

                        var projTreeData = getProjTreeData(projectList);
                        scope.projTreeData = projTreeData;

                        if (!scope.curProjectId){
                            var first = projTreeData[0];
                            if (first.children) {
                                scope.curProjectId = first.children[0].p_projectId;
                                scope.curProject_name = first.children[0].name;
                                scope.curParent = first.id;
                            } else {
                                scope.curProject_name = first.name;
                                scope.curProjectId = first.p_projectId;
                            }
                        }

                        scope.$parent.curProjectId = scope.curProjectId;
                        $tree.tree({
                            data: projTreeData,
                            dragAndDrop: false,
                            useContextMenu: false,
                            //autoOpen: false, //展开级别
                            onCreateLi: function (node, $li) {
                                var hasChildClass = node.children.length > 0 ? 'has-child' : '';
                                if(node.dataType!=2){
                                    $li.find(".jqtree-element").addClass('notproj');
                                }
                                $li.data('tree-item-name',node.name);

                                if (node.id === scope.curParent) {
                                    node.is_open = true;
                                    $li.removeClass('jqtree-closed').find('a').eq(0).removeClass('jqtree-closed');
                                }
                                if (scope.curProjectId && scope.curProjectId.indexOf(node.id) > -1) {
                                    $li.addClass('jqtree-selected');
                                    $li.find(".jqtree-element").before("<span class='checkbox'><input id='" + node.id +"' checked='checked' level='" + node.level
                                        + "' class='" + hasChildClass + "' type='checkbox' value=''><label for='" + node.id + "'>&nbsp;</label></span>");
                                }else{
                                    $li.find(".jqtree-element").before("<span class='checkbox'><input id='" + node.id +"' level='" + node.level
                                        + "' class='" + hasChildClass + "' type='checkbox' value=''><label for='" + node.id + "'>&nbsp;</label></span>");
                                }

                            },
                            //是否可以移动
                            onCanMove: function (node) {
                                return false;
                            },
                            //是否可以移动到
                            onCanMoveTo: function (moved_node, target_node, position) {
                                //只能在同级节点中移动
                                return false;
                            },
                            //移动句柄
                            onIsMoveHandle: function ($ele) {
                                return false;
                            }
                        }).on(
                            'tree.click',
                            function (event) {
                                var node = event.node;
                                event.preventDefault();
                                var node = event.node, checkbox = $('#' + node.id), isCheckedAllSub;

                                if (checkbox.prop("checked")) {
                                    checkbox.prop("checked", false);
                                    node.checked = false;
                                } else {
                                    //只能有一个一级项目，可选一个一级项目下多个分期
                                    if(node.level==1){
                                        $tree.find("input[type=checkbox]").prop("checked", false);
                                    }else{
                                        var checkedLevel_1 = $tree.find("input[type=checkbox]:checked[level=1]")[0],checkedLevel_1_id;
                                        var checkedLevel_2 = $tree.find("input[type=checkbox]:checked[level=2]")[0],checkedLevel_2_id;
                                        if(checkedLevel_2){
                                            checkedLevel_2_id = $(checkedLevel_2).attr('id');
                                        }
                                        if(checkedLevel_1){
                                            checkedLevel_1_id = $(checkedLevel_1).attr('id');
                                        }
                                        var checkedLevel_2_node = $tree.tree('getNodeById', checkedLevel_2_id);

                                        if(checkedLevel_1&&node.parent.id!=checkedLevel_1_id){
                                            $tree.find("input[type=checkbox]").prop("checked", false);
                                        }else if(checkedLevel_2&&node.parent.id!=checkedLevel_2_node.parent.id){
                                            $tree.find("input[type=checkbox]").prop("checked", false);
                                        }
                                    }
                                    checkbox.prop("checked", "checked");
                                    node.checked = true;
                                }
                                //父级节点则子节点全部勾选
                                if (node.children.length > 0) {
                                    checkbox.closest(".jqtree-folder").find("input[type=checkbox]").prop("checked", checkbox.prop("checked"));
                                    _.each(node.children, function (item) {
                                        item.checked = false;
                                    })
                                }
                                //子节点全部勾选则父节点勾选
                                isCheckedAllSub = _.every(node.parent.children, function (item) {
                                    return item.checked == true;
                                });
                                if (isCheckedAllSub) {
                                    $('#' + node.parent.id).prop("checked", "checked");
                                    node.parent.checked = true;
                                }

                                if (!checkbox.prop("checked")) {
                                    $('#' + node.parent.id).prop("checked", false);
                                    node.parent.checked = false;
                                }

                                var checkedProj_id = [],curProject_name=[];
                                _.each($("input[type=checkbox]:checked", $tree), function (item) {
                                    var id = $(item).attr('id');
                                    checkedProj_id.push(id);
                                    var itemData = findProject(id,scope.projTreeData);
                                    if(itemData && itemData.name){
                                        curProject_name.push(itemData.name);
                                    }
                                });
                                scope.curProjectId = checkedProj_id.join();
                                scope.curProject_name = curProject_name.join();
                                scope.$parent.curProjectId = scope.curProjectId ;
                                scope.$parent.$apply();
                            }
                        );

                        $('input.search-box').keyup(function(){
                            var v = $(this).val();
                            var data = angular.copy(scope.projTreeData);
                            var filterData;
                            if (v) {
                                filterData = getFilterTreeData(data, 'name', v);
                                if (filterData.length < 1) {
                                    filterData = [{id: 'nodata', name: '无相关数据'}]
                                }
                            } else {
                                filterData = data;
                            }
                            $tree.tree('loadData',filterData);
                        });

                    }
                });

                /**
                 * 判断元素是否在容器内或容器本身
                 * @param {HTMLElement} container
                 * @param {HTMLElement} target
                 * @returns {*|boolean}
                 */
                function isOrHas(container, target) {
                    return $.contains(container, target) || container === target;
                }
                /**
                 * 展开
                 */
                function open() {
                    projTreeContainer.show();
                    $document.on('click',onDocumentClick);
                }
                /**
                 * 收起
                 */
                function collapse() {
                    projTreeContainer.hide();
                    $document.off('click', onDocumentClick);
                }

                //点击桌面隐藏弹层
                function onDocumentClick(e) {
                    var target = e.target;
                    if ($.contains(element[0],target)) {
                        return;
                    }

                    if (!isOrHas(projTreeInput, target)) {
                        // 如果触发冒泡的元素不在控件元素之内，则将弹出框收起
                        collapse();
                    }

                }

                scope.$on('$destroy', function () {
                    $document.off('click', onDocumentClick);
                    projTreeInput.off('click');
                });


            }
        };
    };

    projectSelector.directive('uiProjectTree', ['$compile', '$document', '$parse', projectDirective]);

    module.exports = projectSelector;
});
